package com.xw.unification.enums;

import com.xw.unification.entity.SignatureCheckContext;
import com.xw.unification.utils.SignatureUtils;

import java.io.UnsupportedEncodingException;
import java.util.Base64;
import java.util.function.BiFunction;

public enum SignatureOperation {
    MD5     ((content, ctx) -> SignatureUtils.digest(DigestType.MD5, content, null, ctx.getCharsetName())),
    SHA1    ((content, ctx) -> SignatureUtils.digest(DigestType.SHA_1, content, ctx.getSignatureKeyValue(), ctx.getCharsetName())),
    SHA256  ((content, ctx) -> SignatureUtils.digest(DigestType.SHA_256, content, ctx.getSignatureKeyValue(), ctx.getCharsetName())),
    BASE64  ((content, ctx) -> {
                try {
                    return Base64.getEncoder().encodeToString(content.getBytes(ctx.getCharsetName()));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }),
    UPPER   ((content, ctx) -> content.toUpperCase()),
    LOWER   ((content, ctx) -> content.toLowerCase())
    ;
    private BiFunction<String, SignatureCheckContext, String> operator;

    SignatureOperation() {
        this(null);
    }

    SignatureOperation(BiFunction<String, SignatureCheckContext, String> operator) {
        this.operator = operator;
    }

    public String apply(String content, SignatureCheckContext checkContext) {
        if (content == null || operator == null || checkContext == null) {
            return content;
        }
        return operator.apply(content, checkContext);
    }
}
